#include<iostream>
#include<cstdio>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h> 
#include"err.hpp"

using namespace std;

static void usage(string proc)
{
    cout<<"Usage\n\t"<<proc<<"serverIp serverPort"<<endl;
}

int main(int argc,char*argv[])
{
    if(argc!=3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    //1. 创建套接字
    int sock=socket(AF_INET,SOCK_STREAM,0);

    //2. 提取server信息
    string serverIp=argv[1];
    uint16_t serverPort=atoi(argv[2]);

    //3. 连接
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverPort);
    inet_aton(serverIp.c_str(),&server.sin_addr);

    int cnt=5;
    while(connect(sock,(struct sockaddr*)&server,sizeof(server)))
    {
        
        cout<<"正在为您重新连接："<<cnt--<<endl;
        if(cnt==0)
        {
            cout<<"连接失败"<<endl;
            exit(CONNECT_ERR);
        }
        sleep(1);
    }


    //连接成功
    while(true)
    {
        string message;
        cout<<"please enter your message# ";
        getline(cin,message);

        //发消息
        write(sock,message.c_str(),message.size());

        //读消息
        char buffer[1024];
        int n=read(sock,buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]='\0';
            cout<<"server echo# "<<buffer<<endl;
        }
        else if(n==0)
        {
            cout<<"server quit,me to"<<endl;
            break;
        }
        else 
        {
            cout<<"clint read error"<<endl;
            break;
        }
    }


    return 0;
}